/**
 *ZHU framework. Copyright 2007-, all rights reserved.
 *
 * $Id$
 * $Revision$
 * $Date$
 * $Author$
 */
package daily.entity;

import java.util.*;

import javax.persistence.*;

import zhu.framework.entity.lifecycle.*;

import com.google.common.collect.*;

import daily.entity.security.*;

/**
 * @author xiaopengzhu
 * 
 */
public class StaffGroupLifecycle extends AbstractLifecycle<StaffGroup> {

	public StaffGroupLifecycle(final LifecycleContext lifecycleContext) {
		super(lifecycleContext);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see zhu.framework.entity.lifecycle.Lifecycle#getEntityType()
	 */
	@Override
	public Class<StaffGroup> getEntityType() {
		return StaffGroup.class;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see zhu.framework.entity.lifecycle.Lifecycle#newInstance()
	 */
	@Override
	public StaffGroup newInstance() {
		return new StaffGroup();
	}

	public List<StaffGroup> findAll() {
		final StringBuilder buf = new StringBuilder();
		buf.append(" select o from StaffGroup o ");
		buf.append(" order by o.index ");
		final Query query = getEntityManager().createQuery(buf.toString());
		return getQueryResultList(query);
	}

	public SecurityRole findByStaffAndFunction(final Staff staff, final Function function) {
		final StringBuilder buf = new StringBuilder();
		buf.append(" select ss.securityRole from StaffGroup o ");
		buf.append(" join o.staffs s ");
		buf.append(" join o.functionSecuritySettings ss ");
		buf.append(" where s = :theStaff ");
		buf.append(" and ss.function = :theFunction ");
		final Query query = getEntityManager().createQuery(buf.toString());
		query.setParameter("theStaff", staff);
		query.setParameter("theFunction", function);
		final List<SecurityRole> queryResultList = getQueryResultList(query);
		final List<SecurityRole> list = Lists.newArrayList(queryResultList);
		Collections.sort(list);
		if (list.isEmpty()) {
			return SecurityRole.ALPERSONAL;
		}
		return list.get(0);
	}
}
